import { NextRequest, NextResponse } from 'next/server';
import { readCategories, writeCategories } from '@/lib/data';
import { verifyToken } from '@/lib/auth';

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { name } = await request.json();
    const categories = readCategories();
    const category = categories.find(c => c.id === params.id);

    if (!category) {
      return NextResponse.json(
        { success: false, message: '分类不存在' },
        { status: 404 }
      );
    }

    category.name = name;
    // 更新路径
    const parent = category.parentId ? categories.find(c => c.id === category.parentId) : null;
    category.path = parent ? `${parent.path}/${name}` : name;

    writeCategories(categories);

    return NextResponse.json({ success: true, category });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '更新分类失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const categories = readCategories();
    
    // 检查是否有子分类
    const hasChildren = categories.some(c => c.parentId === params.id);
    if (hasChildren) {
      return NextResponse.json(
        { success: false, message: '该分类下还有子分类，无法删除' },
        { status: 400 }
      );
    }

    const filtered = categories.filter(c => c.id !== params.id);
    writeCategories(filtered);

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '删除分类失败' },
      { status: 500 }
    );
  }
}

